package com.lidong.photopicker;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.lidong.photopicker.widget.ViewPagerFixed;

import java.security.acl.LastOwnerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by foamtrace on 2015/8/25.
 */
public class PhotoPreviewActivity extends AppCompatActivity implements PhotoPagerAdapter.PhotoViewClickListener{

    public static final String EXTRA_PHOTOS = "extra_photos";
    public static final String EXTRA_CURRENT_ITEM = "extra_current_item";

    /** 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合  */
    public static final String EXTRA_RESULT = "preview_result";

    /** 预览请求状态码 */
    public static final int REQUEST_PREVIEW = 99;

    private ArrayList<String> paths;
    private ViewPagerFixed mViewPager;
    private PhotoPagerAdapter mPagerAdapter;
    private int currentItem = 0;
    private CheckBox mPickCheck;
    private Button mCheckBut;
    private int currentNum;
    private int count=0;

    private Map<Integer,Boolean> isCheckMap;
    private int mSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_image_preview);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.setStatusBarColor(getResources().getColor(R.color.heard_background));
                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        initViews();
        isCheckMap=new HashMap<>();
        paths = new ArrayList<>();
        final ArrayList<String> pathArr = getIntent().getStringArrayListExtra(EXTRA_PHOTOS);
        mSize = pathArr.size();
        if (pathArr.contains("000000")){
            //预览的时候，在选定数量不足6张时 不显示最后的空图片
            pathArr.remove("000000");
        }

        if(pathArr != null){
            paths.addAll(pathArr);
        }

        currentItem = getIntent().getIntExtra(EXTRA_CURRENT_ITEM, 0);

        mPagerAdapter = new PhotoPagerAdapter(this, paths);
        mPagerAdapter.setPhotoViewClickListener(this);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(currentItem);
        mViewPager.setOffscreenPageLimit(5);
        //设置显示的图片
        setShowPic();
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                updateActionBarTitle();

            }

            @Override
            public void onPageSelected(int position) {

                if (isCheckMap.get(mViewPager.getCurrentItem())){
                    mPickCheck.setChecked(true);

                }else {
                    mPickCheck.setChecked(false);
                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        updateActionBarTitle();

        //最终选择照片结果
        selectorPicFinish();

    }
    //最终选择照片结果
    private void selectorPicFinish() {
      final  Map<Integer,String> indexMap=new HashMap<Integer, String>();
        for (int i=0;i<paths.size();i++){
            indexMap.put(i,paths.get(i));
        }
        //点击图片实现最终确定的图片
        mCheckBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i=0;i<mSize;i++){
                   // Boolean isCheck = isCheckMap.get(i);
                    Log.e("MLOG",isCheckMap.toString());
                    Log.e("MLOG",String.valueOf(isCheckMap.get(i)));
                    if (!isCheckMap.get(i)){
                        Log.e("MLOG",String.valueOf(i));
                        paths.remove(indexMap.get(i));
                    }
                }

                onBackPressed();
            }
        });


    }

    //设置显示的图片
    private void setShowPic() {
        mCheckBut.setText("确定("+String.valueOf(paths.size())+")");
        for (int i=0;i<paths.size();i++){
            isCheckMap.put(i,true);

        }
        mPickCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentNum = mViewPager.getCurrentItem();
                if (!mPickCheck.isChecked()){    //取消选中
                    count++;
                   // Log.i("MLOG",String.valueOf(currentNum));
                    isCheckMap.put(currentNum,false);
                }else {
                    isCheckMap.put(currentNum,true);
                    count--;

                }
                if (count==paths.size()){
                    mCheckBut.setText("确定");
                }else {

                    mCheckBut.setText("确定(" +String.valueOf(paths.size()-count)+")");

                }
            }
        });

    }

    private void initViews(){
        mViewPager = (ViewPagerFixed) findViewById(R.id.vp_photos);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.pickerToolbar);
        mPickCheck = (CheckBox) findViewById(R.id.picker_check);
        mCheckBut = (Button) findViewById(R.id.preview_button);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void OnPhotoTapListener(View view, float v, float v1) {
        onBackPressed();
    }

    public void updateActionBarTitle() {
        getSupportActionBar().setTitle(
                getString(R.string.image_index, mViewPager.getCurrentItem() + 1, paths.size()));

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_RESULT, paths);
        setResult(RESULT_OK, intent);
        finish();
        super.onBackPressed();
    }

}
